package com.backend.utils;

import com.backend.properties.EmailProperties;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

public class MailUtil {
    public static boolean sendMail(EmailProperties emailProperties, String to, String title, String content) {
        // 从配置类获取配置

        Properties properties = new Properties();
        properties.put("mail.smtp.host", emailProperties.getHost());
        properties.put("mail.smtp.port", emailProperties.getPort());  // 465 或 587
        properties.put("mail.smtp.auth", "true");

        // 启用 SSL/TLS
        properties.put("mail.smtp.ssl.enable", "true");

        // 创建邮件会话
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailProperties.getUser(), emailProperties.getCode());
            }
        });

        try {
            // 创建邮件
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(emailProperties.getUser()));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(title);
            message.setText(content);

            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return true;
    }
}
